package com.huawei.bitfun.actions;

import com.intellij.openapi.actionSystem.ActionUpdateThread;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.command.WriteCommandAction;
import org.jetbrains.annotations.NotNull;

public class OptimizeSnippets extends AnAction {
    private static final String CODES = """
        set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsave-optimization-record")
        set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fsave-optimization-record")
        
        set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -O1")
        set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -O1")
        """;

    @Override
    public void actionPerformed(@NotNull AnActionEvent event) {
        var editor = event.getData(PlatformDataKeys.EDITOR);
        if (editor == null) {
            return;
        }
        WriteCommandAction.runWriteCommandAction(getEventProject(event), () -> {
           var document = editor.getDocument();
           var textLength = document.getText().length();
           document.insertString(textLength, CODES);
        });
    }

    @Override
    public @NotNull ActionUpdateThread getActionUpdateThread() {
        return super.getActionUpdateThread();
    }

    @Override
    public void update(@NotNull AnActionEvent event) {
        var editor = event.getData(PlatformDataKeys.EDITOR);
        var file = event.getData(PlatformDataKeys.VIRTUAL_FILE);
        if (editor != null && file != null) {
            var fileName = file.getName();
            if (fileName.endsWith(".cmake") || fileName.equalsIgnoreCase("CMakeLists.txt")) {
                event.getPresentation().setVisible(true);
                return;
            }
        }
        event.getPresentation().setVisible(false);
    }
}